package com.duan.laugh.file.util;

import cn.hutool.core.util.StrUtil;
import com.duan.laugh.common.core.exception.DownloadFileException;
import com.duan.laugh.common.security.util.UserUtils;
import com.duan.laugh.starter.minio.constants.MinioConstants;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * 文件工具类
 *
 * @author duanjw
 */
@Slf4j
@UtilityClass
public class FileUtil {
    /**
     * 流的方式下载文件
     * @param request
     * @param response
     * @param inputStream
     * @param filename
     */
    @SneakyThrows
    public void download(HttpServletRequest request, HttpServletResponse response, InputStream inputStream, String filename) {
        // 文件名编码，解决中文文件名乱码
        filename = encodeFilename(request, filename);
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
        inputStream.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        response.setContentType("application/octet-stream");
        try (OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
            outputStream.write(buffer);
        } catch (IOException e) {
            new DownloadFileException();
        }
    }

    /**
     * 文件名编码，解决中午文件名乱码
     * @param request
     * @param filename
     * @return
     */
    @SneakyThrows
    public String encodeFilename(HttpServletRequest request, String filename) {
        String userAgent = request.getHeader(MinioConstants.USER_AGENT);
        // 针对IE或者以IE为内核的浏览器，postman也需要编码，但是编码后还是乱码，不编码下载的文件不对
        if (StrUtil.containsAnyIgnoreCase(userAgent, MinioConstants.IE_CORE) || userAgent.contains(MinioConstants.POSTMAN_CORE)) {
            filename = java.net.URLEncoder.encode(filename, MinioConstants.CHARSET_UTF_8);
        } else {
            // 非IE浏览器的处理：
            filename = new String(filename.getBytes(MinioConstants.CHARSET_UTF_8), MinioConstants.CHARSET_ISO_8859_1);
        }
        return filename;
    }

    /**
     * 获取bucket名称
     *
     * 用户的租户id
     *
     * @return
     */
    public String getBucketName() {
        return String.valueOf(UserUtils.getUser().getTenantId());
    }
}
